package mobi.hami.huapin.service.impl;

import com.alibaba.fastjson.JSON;
import mobi.hami.huapin.base.Result;
import mobi.hami.huapin.constants.BaseEnums;
import mobi.hami.huapin.dao.UserSessionMapper;
import mobi.hami.huapin.model.UserInfo;
import mobi.hami.huapin.model.UserSession;
import mobi.hami.huapin.model.UserWechat;
import mobi.hami.huapin.service.UserInfoService;
import mobi.hami.huapin.service.UserWechatService;
import mobi.hami.huapin.service.WxauthorizeService;
import mobi.hami.huapin.util.HttpUtil;
import mobi.hami.huapin.util.Results;
import mobi.hami.huapin.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信授权相关业务
 */
@Service
public class WxauthorizeServiceImpl implements WxauthorizeService {

    private static final Logger logger = LoggerFactory.getLogger(WxauthorizeServiceImpl.class);

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserWechatService userWechatService;

    @Value("#{weixinProperties['wx.appid']}")
    public String appId;

    @Value("#{weixinProperties['wx.secret']}")
    public String secret;

    @Autowired
    private UserSessionMapper userSessionMapper;

    /**
     * 授权code
     * @param loginCode
     * @return
     */
    public Result wxauthorize(String loginCode){

        if(StringUtil.isEmpty(loginCode)){
            return Results.failure();
        }

        String  res = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appId+"&secret="+secret+"&js_code="+loginCode+"&grant_type=authorization_code";
        try {
            res = HttpUtil.get(url);
        }catch(Exception e){
            e.printStackTrace();
        }

        if(StringUtil.isNotEmpty(res)){
            Map<String,String> mm = new  HashMap<String,String>();
            mm=JSON.parseObject(res,mm.getClass());
            if(!mm.containsKey("errcode")){
                String session_key = mm.get("session_key");
                String openid = mm.get("openid");
                String unionid = mm.get("unionid");
                UserWechat uwechat=userWechatService.selectOneByWechatSmallId(openid);
                if(null == uwechat){
                    UserInfo ufo = new UserInfo();
                    ufo.setCreate_time(new Date());
                    userInfoService.saveUserInfo(ufo);
                    UserWechat wchat = new UserWechat();
                    wchat.setUser_id(ufo.getId());
                    wchat.setWechat_small_id(openid);
                    wchat.setCreate_time(new Date());
                    wchat.setWechat_union_id(unionid);
                    wchat.setIs_valid(1);
                    wchat.setWechat_public_id(appId);
                    wchat.setLaunch_collage_count(0);
                    wchat.setPartack_collage_count(0);
                    userWechatService.save(wchat);
                    updateSession(openid,ufo.getId());
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("id",ufo.getId());
                    map.put("nickName",null);
                    map.put("head_photo",null);
                    map.put("unionId",unionid);
                    map.put("wechat_small_id",openid);
                    map.put("wechat_public_id",null);
                    map.put("session_key",session_key);
                    map.put("appId",appId);
                    map.put("secret",secret);
                    map.put("address_id",ufo.getAddress_id());
                    map.put("consignee_id",ufo.getConsignee_id());
                    map.put("partack_collage_count",0);
                    map.put("launch_collage_count",0);
                    map.put("phone",null);
                    map.put("self_collage_count",0);
                    return Results.successWithData(map, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
                }else{
                    UserInfo uo = userInfoService.selectOnebyId(uwechat.getUser_id());
                    if(null == uo){
                        return Results.failure("userInfo is null");
                    }
                    updateSession(openid,uo.getId());
                    Map<String,Object> map = new HashMap<String,Object>();
                    map.put("id",uwechat.getUser_id());
                    map.put("nickName",uwechat.getNick_name());
                    map.put("head_photo",uwechat.getHead_photo());
                    map.put("unionId",uwechat.getWechat_union_id());
                    map.put("wechat_small_id",uwechat.getWechat_small_id());
                    map.put("wechat_public_id",uwechat.getWechat_public_id());
                    map.put("session_key",session_key);
                    map.put("appId",appId);
                    map.put("secret",secret);
                    map.put("address_id",uo.getAddress_id());
                    map.put("consignee_id",uo.getConsignee_id());
                    map.put("partack_collage_count",uwechat.getPartack_collage_count());
                    map.put("launch_collage_count",uwechat.getLaunch_collage_count());
                    map.put("phone",uo.getPhone());
                    map.put("self_collage_count",uwechat.getSelf_collage_count());
                    return Results.successWithData(map, BaseEnums.SUCCESS.code(), BaseEnums.SUCCESS.desc());
                }
            }else {
                return Results.failure("code无效");
            }
        }
        return Results.failure();
    }

    /**
     * updateSession
     * @param open_id
     * @param user_id
     * @return
     */
    public Integer updateSession(String open_id,Integer user_id){
        UserSession session = userSessionMapper.findBy(open_id,user_id);
        if(null == session){
            return userSessionMapper.insert(new UserSession(user_id,open_id,new Date(),new Date(),new Date()));
        }
        Date last_login_time = session.getLogin_time();
        session.setLast_login_time(last_login_time);
        session.setLogin_time(new Date());
        return userSessionMapper.updateByPrimaryKeySelective(session);
    }
}
